package com.woniuxy.controller;

import com.woniuxy.common.Result;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //直接使用会话域
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpServletRequest request;
    /**
     * 登录
     */
    //@PostMapping 注解包含了 @RequestMapping 和 @ResponseBody 注解
    @PostMapping("/login")
    public Result<User> login(@RequestBody User param){
        //调用业务层
        Result<User> result = userService.login(param);
        //判断是否登录成功
        if (result.getCode() == 1){
            //保存用户信息到会话域
            session.setAttribute("user",result.getData());
        }
        return result;
    }
    /**
     * 退出
     */
    @RequestMapping("/logout")
    public void logout() throws IOException {
         if (session !=null){
             //会话过期
             session.invalidate();
             //2.设置响应头，清除缓存
             response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
             response.setHeader("Pragma", "no-cache");
             response.setHeader("Expires", "0");
             //3.跳转到登录页面, request.getContextPath() 获取模块或项目的访问地址
             response.sendRedirect(request.getContextPath() + "/index.html");
         }
    }
}
